#include <stdio.h>
#include "MemoryStack.h"

class MemoryStackObj
{
public:
	void* operator new(size_t size, MemoryStack* stack)
	{
		return stack->push(size); //object is pushed onto memory stack
	}

	void operator delete(void* p, MemoryStack* stack)
	{
		//stack->pop(); //this could lead to problems if delete is called in the wrong order on the objects in the stack.
	}
};

class BaseClass : public MemoryStackObj
{
public:
	short member;
	BaseClass()
	{
		member=0xffff;
	}

	BaseClass(short a)
	{
		member=a;
	}
	
	~BaseClass()
	{
		member=0xcdcd; //reset for debugging in memory view
	}
};

class DerivedClass : public BaseClass
{
public:
	int member2;
	DerivedClass()
	{
		member2=0xffffffff;
	}

	DerivedClass(short a, int b)
	{
		member=a;
		member2=b;
	}

	~DerivedClass()
	{
		member2=0xcdcdcdcd; //reset for debugging in memory view
	}
};

int main(int argc, char* argv[])
{
	MemoryStack* stack = new MemoryStack(100, 4);

	BaseClass* b1 = new (stack) BaseClass(0x11b1);
	BaseClass* b2 = new (stack) BaseClass(0x22b2);
	DerivedClass* d1 = new (stack) DerivedClass(0x11d1, 0x78563412);
	BaseClass* b3 = new (stack) BaseClass(0x33b3);
	

	//Destructors need to be called explicitly before removing the object from the stack
	//The objects need to be destructed in reverse order of construction, because a stack is a LIFO data structure
	b3->~BaseClass();
	stack->pop();	
	
	d1->~DerivedClass();
	stack->pop();

	b2->~BaseClass();
	stack->pop();

	b1->~BaseClass();
	stack->pop();
	
	DerivedClass* d2 = new (stack) DerivedClass(0x22d2, 0x78563412); //should be at the beginning of the stack
	d2->~DerivedClass();

	delete stack;

	return 0;
}